package com.lw.leetcode.stack.b;

import java.util.Stack;

/**
 * stack
 * 856. 括号的分数
 *
 * @Author liw
 * @Date 2021/6/12 21:06
 * @Version 1.0
 */
public class ScoreOfParentheses {

    public static void main(String[] args){
        ScoreOfParentheses test = new ScoreOfParentheses();
//        String str = "(()(()))";
//        String str = "(())";
//        String str = "()()";
//        String str = "()";
        String str = "(((()()))())()()(((()))())((()(())())())()()";
        int i = test.scoreOfParentheses(str);
        System.out.println(i);
    }

    public int scoreOfParentheses(String s) {
        Stack<Integer> stack =  new Stack<>();
        char[] arr = s.toCharArray();
        int length = s.length();
        for (int i = 0; i < length; i++) {
            char c = arr[i];
            if (c == '(') {
                stack.push(0);
            } else {
                if (stack.peek() == 0) {
                    stack.pop();
                    stack.push(1);
                } else {
                    int sum = 0;
                    int value;
                    while ((value = stack.pop()) != 0) {
                        sum += value;
                    }
                    stack.push(sum << 1);
                }
            }
        }
        int sum = 0;
        while (!stack.isEmpty()) {
            sum += stack.pop();
        }
        return sum;
    }

}
